package mqtt;

import org.eclipse.paho.mqttv5.client.*;
import org.eclipse.paho.mqttv5.client.persist.MemoryPersistence;
import org.eclipse.paho.mqttv5.common.MqttException;
import org.eclipse.paho.mqttv5.common.MqttMessage;
import org.eclipse.paho.mqttv5.common.packet.MqttProperties;

public class Subscribe01 {
    public static void main(String[] args) {
        String broker = "tcp://127.0.0.1:1883";
        String topic = "topic1";
        String username = "admin";
        String password = "admin";
        String clientid = "subscribe_client01";
        int qos = 0;

        try {
            MqttClient client = new MqttClient(broker, clientid, new MemoryPersistence());
            // 连接参数
            MqttConnectionOptions options = new MqttConnectionOptions();
            options.setUserName(username);
            options.setPassword(password.getBytes());
            options.setConnectionTimeout(60);
            options.setKeepAliveInterval(60);
            // 设置回调
            client.setCallback(new MqttCallback() {
                @Override
                public void disconnected(MqttDisconnectResponse mqttDisconnectResponse) {
                    mqttDisconnectResponse.getException();
                }

                @Override
                public void mqttErrorOccurred(MqttException e) {
                    System.out.println(e.getMessage());
                }

                public void messageArrived(String topic, MqttMessage message) {
                    System.out.println("topic: " + topic);
                    System.out.println("Qos: " + message.getQos());
                    System.out.println("message content: " + new String(message.getPayload()));

                }
                //完成时执行
                @Override
                public void connectComplete(boolean b, String s) {
                    System.out.println("connectIp:"+s);
                }

                @Override
                public void authPacketArrived(int i, MqttProperties mqttProperties) {

                }
                @Override
                public void deliveryComplete(IMqttToken iMqttToken) {
                    System.out.println("deliveryComplete---------" + iMqttToken.isComplete());
                }
            });
            //客户端进行连接
            client.connect(options);
            //客户端进行订阅
            client.subscribe(topic, qos);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
